<template>
	<view class="container">
		<checkbox-group name="" @change="onChange2" >
			<view v-for="(item,index) in list" :key="item.id">
				<checkbox :value="item.id" :checked="item.checked" />
				<text class="name">{{item.name}}</text>
				<text class="price">{{item.price}}</text>
				<text class="del" @click="delItem(item.id)" >删除</text>
			</view>
		</checkbox-group>
		<view class="card">
			<view class="text">
				选中{{selectedItems.length}}个产品，总价{{sumPrice}}元。
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	const list = ref([
		{id:'11',name:'小米',price:4999,checked:false},
		{id:'22',name:'华为',price:6899,checked:false},
		{id:'33',name:'oppo',price:2988,checked:false},
		{id:'44',name:'苹果',price:9888,checked:false},
	])
	const sumPrice = ref()
	const selectedItems = ref([])
	const onChange = (e)=>{
		// console.log(e);
		selectedItems.value = e.detail.value
		// console.log(selectedItems.value);
		sumPri()
	}
	const sumPri= ()=>{
		sumPrice.value =  list.value.filter(item=>{
			return selectedItems.value.includes(item.id)
		}).reduce((sum,prev)=>sum+=prev.price,0)
		// console.log(newList.value);
		// sumPrice.value =  newList.value
		// console.log(sumPrice.value);
		return sumPrice
	}
	// const newList= ref([])
	const delItem = (id)=>{ 
		list.value = list.value.filter(item=>item.id !== id)
		sumPri()
	}
	const onChange2 = (e)=>{ 
		selectedItems.value = e.detail.value
		console.log(selectedItems.value);
		list.value.forEach(item=>{
			item.checked = selectedItems.value.includes(item.id) 
		})
		sumPrice.value = list.value.filter(item=>item.checked == true).reduce((prev,current)=>prev+current.price,0)
		console.log(sumPrice.value);
	}
</script>

<style lang="scss" scoped>
	.container{
		.del{
			margin-left: 20px;
			color: red;
			padding: 4px;
			box-sizing: border-box;
			position: relative;
			right: 0px;
		}
	}
	
</style>
